package controllers

import java.io.File
import java.nio.file.Files

import dao._
import javax.inject.Inject
import play.api.data._
import play.api.data.Forms._
import play.api.libs.json.Json
import play.api.mvc._
import utils.Utils
import play.api.libs.concurrent.Execution.Implicits._
import models.Tables._
import org.apache.commons.io.FileUtils
import org.joda.time.DateTime

import scala.concurrent.Future

/**
  * Created by yz on 2018/5/23
  */
case class UserData(projectName: String, password: String)

class ProjectController @Inject()(projectDao: ProjectDao, tool: Tool, groupDao: GroupDao) extends Controller {

  def loginBefore = Action { implicit request =>
    Ok(views.html.login())
  }

  def logout = Action {
    Redirect(routes.ProjectController.loginBefore()).flashing("info" -> "退出登录成功!").withNewSession
  }

  val userForm = Form(
    mapping(
      "projectName" -> text,
      "password" -> text
    )(UserData.apply)(UserData.unapply)
  )

    def login = Action.async { implicit request =>
      val data = userForm.bindFromRequest.get
      projectDao.selectByUserData(data).map { x =>
        if (x.isDefined) {
            Redirect(routes.MetaboliteController.toIndex()+"?projectId="+x.get.id).withSession(request.session + ("user" -> data.projectName))
        } else {
          Redirect(routes.ProjectController.loginBefore()).flashing("info" -> "项目名或密码错误!")
        }
      }
    }


}
